package com.example.controller;

import com.example.Exception.InvalidOpenidException;
import com.example.Utils.LoggerUtils;
import com.example.Utils.UserHolder;
import com.example.enums.Message;
import com.example.model.LoginRequest;
import com.example.model.Result;
import com.example.model.User;
import com.example.service.IUserService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Hello
 * @since 2024-07-03
 */
@RestController
@RequestMapping("/user")
@Api
public class UserController {
    private static final Logger logger = LoggerUtils.getLogger(UserController.class);
    @Autowired
    IUserService iUserService;


    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginRequest loginRequest) {
        // 处理登录逻辑
        String code = loginRequest.getCode();
        String token = null;
        try {
            token = iUserService.login(code);
        } catch (InvalidOpenidException e) {
            return Result.fail(Message.INVALID_OPENID);
        }
        return Result.success(token,Message.SUCCESS);
    }
    //更新用户信息
    @PostMapping("/update")
    public Result<String> update(@RequestBody User user) {
        logger.info("头像的base64：{}",user.getWechatAvatar());
        User loginUser = UserHolder.getUser();
        logger.info("这次登录的user的openid：{}",loginUser.getWechatOpenid());

        if(!iUserService.updateUser(loginUser.getWechatOpenid(),user)) {
            return Result.fail(Message.COMMIT_FAIL_ERROR);
        }

        //对用户信息进行更新
        return Result.success("成功");
    }
    //获取用户信息
    @GetMapping("/getInfo")
    Result<User> getInfo() {
        User loginUser = UserHolder.getUser();
        User info = iUserService.getInfo(loginUser.getWechatOpenid());
        if(info == null) return Result.fail("失败");
        //避免把openid传给前端
        info.setWechatOpenid("null");
        info.setWechatUnionid("null");
        return Result.success(info);
    }

    @GetMapping("/getPoints")
    public Result<Integer> getPoints(){
        User loginUser=UserHolder.getUser();

        if(loginUser==null){
            return Result.fail("获取用户积分时获取用户openid失败");
        }
        return Result.success(iUserService.getPoints(loginUser));
    }



}
